# -*- coding:utf-8 -*-
'''eof
name:小额贷款公司未结清贷款笔数
code:SmallLoan_UnpaidLoanCnt
tableName:
columnName:
groups:准入>个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''

'''
ICRLoanInfo002*Loan 贷款信息明细表
State 账户状态
FinanceType 授信机构类型
若字段为空，则指标值返回空，否则指标值取该值.
指标值 = count（账户状态为“未结清”&授信机构类型为"小额信贷公司"）的贷款笔数
'''


import sys
import json
reload(sys)
sys.setdefaultencoding('utf-8')




def SmallLoan_UnpaidLoanCnt():
    null_type_list = ['', None, 'null', '/', 'Null','NULL','--','-']
    nostate_type = [u'正常',u'逾期',u'呆账']
    yesstate_type=[u'结清',u'转出']
    state_type=nostate_type+yesstate_type
    nonsmall_com=[u'财务公司',u'村镇银行',u'机构',u'汽车金融公司',u'商业银行',u'外资银行',u'消费金融公司',
                  u'信托投资公司',u'住房储蓄银行']
    com_type=[u'财务公司',u'村镇银行',u'机构',u'汽车金融公司',u'商业银行',u'外资银行',u'消费金融公司',
              u'信托投资公司',u'住房储蓄银行',u'小额信贷公司']
    count = []
    try:
        if IC in null_type_list :
            return u'缺失值'
        if len(IC) == 0:
            return u'缺失值'
        icr = json.loads(IC[0]["icr"])
        if icr in null_type_list:
            return u'缺失值'
        if len(icr) == 0:
            return u'缺失值'
        if icr.has_key('ICRLoanInfo002*Loan') and len(icr['ICRLoanInfo002*Loan']) >= 1:
            for i in icr['ICRLoanInfo002*Loan']:
                if i.has_key('State') and  i.has_key('FinanceType') :
                    if i['State'] in nostate_type and i['FinanceType'] == u'小额信贷公司':
                        count.append(1)
                    elif  i['State'] in state_type and i['FinanceType'] in nonsmall_com:
                        count.append(0)
                    elif i['State'] in yesstate_type and i['FinanceType'] in com_type:
                        count.append(0)
                    else:
                        count.append(None)
                else:
                    count.append(None)
        else:
            return u'缺失值'
        #若count均为None,则返回缺失值,否则将None置为0
        small_count = filter(lambda x: x is not None, count)
        return sum(small_count) if len(small_count) != 0 else u'缺失值'
    except:
        return u'缺失值'


result = SmallLoan_UnpaidLoanCnt()
